<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .container {
            position: relative;
            display: flex;
            margin: 50px auto;
            width: 400px;
            height: 50px;
            box-shadow: 0 0 1px 1px;
        }

        .bg {
            width: 0;
            height: 50px;
            background-color: palegreen;
            opacity: 0.8;
        }

        .text {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            line-height: 50px;
            text-align: center;
            z-index: -1;
        }

        .item {
            width: 50px;
            height: 50px;
            background-color: pink;
        }

        .item:hover {
            cursor: move;
        }
    </style>
</head>
<body>
<div class="container" id="container">
    <div class="bg" id="bg"></div>
    <div class="text">请按住滑块，拖动到最右边</div>
    <div class="item" id="item"></div>
</div>
<script>
    const container = document.getElementById('container');
    const bg = document.getElementById('bg');

    function init() {
        const item = document.getElementById('item');
        item.onmousedown = mousedown;
    }

    function mousedown(e) {
        this.distanceLeft = e.clientX - (this.moveX || 0);
        document.onmousemove = mousemove.bind(this);
        document.onmouseup = mouseup.bind(this);
    }

    function mousemove(e) {
        this.moveX = e.clientX - this.distanceLeft;
        if (this.moveX < 0) {
            this.moveX = 0;
        } else if (this.moveX > (container.clientWidth - this.clientWidth)) {
            this.moveX = container.clientWidth - this.clientWidth;
        }
        // this.style.transform = `translate(${this.moveX}px,0px)`;
        bg.style.width = `${this.moveX}px`;
    }

    function mouseup() {
        document.onmousemove = null;
        document.onmouseup = null;
    }

    init()
</script>
</body>
</html>